from flask import Blueprint, request, jsonify, current_app
from werkzeug.exceptions import BadRequest, UnsupportedMediaType
from app.models.user import User
from app.extensions import db
from pymysql import IntegrityError
import traceback

user_bp = Blueprint('user', __name__)


@user_bp.route('/user_login', methods=['POST'])
def login():
    if not request.is_json:
        raise UnsupportedMediaType()
    try:
        data = request.get_json()
        if not data or 'username' not in data or 'password' not in data:
            raise BadRequest('Missing username or password field')
        user = User.query.filter_by(username=data['username']).first()
        if user:
            if user.check_password(data['password']):
                # 移除JWT相关代码，可根据需求返回其他信息
                user_info = {
                    "userId": str(user.user_id),
                    "username": user.username,
                    "nickname": user.username,
                    "roles": user.role,
                    "email": user.email,
                    "message": "登录成功"
                }
                return jsonify(user_info)
            else:
                current_app.logger.warning(f"登录失败：用户 {user.username} 密码错误")
                return jsonify({'code': 404, 'message': f"登录失败：用户 {user.username} 密码错误"}), 404
        else:
            current_app.logger.warning(f"登录失败：用户名不存在（尝试用户名：{data['username']}）")
            return jsonify({'code': 404, 'message': f"登录失败：用户名不存在（尝试用户名：{data['username']}）"}), 404
    except Exception as e:
        current_app.logger.error(f'登录异常: {str(e)}')
        return jsonify({'code': 500, 'message': '服务器内部错误'}), 500

@user_bp.route('/user_register', methods=['POST'])
def register():
    try:
        # 请求格式验证
        if not request.is_json:
            raise UnsupportedMediaType()

        data = request.get_json()

        # 必要字段检查
        required_fields = ['username', 'password']
        if not all(field in data for field in required_fields):
            raise BadRequest('缺少用户名或密码字段')

        # 数据清洗
        username = data['username'].strip()
        password = data['password'].strip()
        email = data['email'].strip()

        # 有效性验证
        if not username or not password:
            raise BadRequest('用户名和密码不能为空')

        if len(username) < 4:
            raise BadRequest('用户名至少需要4个字符')

        if len(password) < 8:
            raise BadRequest('密码至少需要8个字符')

        # 用户名查重
        if User.query.filter_by(username=username).first():
            raise BadRequest('用户名已被注册')

        # 创建用户，补充role默认值，若email非必填可按需处理
        new_user = User(username=username, role='user', email=email)
        new_user.set_password(password)

        db.session.add(new_user)
        db.session.commit()

        return jsonify({
            'code': 200,
            'message': '注册成功',
            'data': {
                'user_id': new_user.user_id,
                'username': new_user.username,
                'email': new_user.email
            }
        }), 200

    except (UnsupportedMediaType, BadRequest) as e:
        # 客户端错误（4xx）
        error_code = e.code if hasattr(e, 'code') else 400
        current_app.logger.warning(f'注册验证失败: {str(e)}')
        return jsonify({
            'code': error_code,
            'message': str(e)
        }), error_code

    except IntegrityError as e:
        # 数据库唯一性约束错误
        db.session.rollback()
        current_app.logger.error(f'数据库完整性错误: {str(e)}')
        return jsonify({
            'code': 409,
            'message': '用户名已被注册'
        }), 409

    except Exception as e:
        # 服务器错误（5xx）
        db.session.rollback()
        current_app.logger.error(f'注册系统错误: {str(e)}\n{traceback.format_exc()}')
        return jsonify({
            'code': 500,
            'message': '服务器内部错误'
        }), 500

@user_bp.route('/get_users', methods=['GET'])
# @jwt_required()
def get_users():
    users = User.query.all()
    return jsonify([{
        "id": user.user_id,
        "username": user.username,
        "email": user.email

    } for user in users]), 200
